﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace Microsoft.SqlCommunity.SQLRSS
{
    /// <summary>
    /// A class that represents ancillary tables used to provide extra data to join with 
    /// with data from tables whos changes are being track.
    /// </summary>
    public class ReferenceTableDescription : ObjectDescription
    {

        // Create the reference table from XML description in the XML configuration file.
        public ReferenceTableDescription(Connection parentDataConnection, XElement referenceTableElement) 
            : base(parentDataConnection, referenceTableElement)
        {
            this.Name = AttributeValueOrNull(referenceTableElement, "Name");
            InitializeLocalMembers(referenceTableElement, parentDataConnection);
        }

        // Set the data members of this class based on the appropriate ReferenceTable element in the XML configuration file.
        protected override void InitializeLocalMembers(XElement referenceTableElement, Connection parentDataConnection)
        {
            base.InitializeLocalMembers(referenceTableElement, parentDataConnection);
        }

        // If the configuration file changes, merge those changes into the existing object that represents the reference table.
        public static ReferenceTableDescription MergeTableDescription(XElement tableElement, ReferenceTableDescription currentTableDescription, Connection parentConnection)
        {
            if (currentTableDescription == null)
                return new ReferenceTableDescription(parentConnection, tableElement);
            else
            {
                currentTableDescription.ExecuteWithLock(LockType.Write,
                    () => { currentTableDescription.InitializeLocalMembers(tableElement, parentConnection); });
                return currentTableDescription;
            }
        }

    }
}
